package yiran.itemuse.command;

import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import yiran.itemuse.ConfigManager;
import yiran.itemuse.Itemuse;
import yiran.itemuse.data.ItemCommandService;
import yiran.itemuse.lang.LangHelper;
import yiran.itemuse.data.ItemCommandService.CommandData;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ItemCommandExecutor implements CommandExecutor, TabCompleter {
    private final Itemuse plugin;
    private final ItemCommandService commandService = new ItemCommandService();

    public ItemCommandExecutor(Itemuse plugin) {
        this.plugin = plugin;
    }

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        if (!sender.hasPermission("yiran.itembind.use")) {
            sender.sendMessage(LangHelper.getString("errors.no-permission"));
            return true;
        }

        if (args.length == 0) {
            sendUsage(sender);
            return true;
        }

        switch (args[0].toLowerCase()) {
            case "bind":
                return handleBindCommand(sender, args);
            case "remove":
                return handleRemoveCommand(sender);
            case "list":
                return handleListCommand(sender);
            case "reload":
                return handleReloadCommand(sender);
            default:
                sendUsage(sender);
                return true;
        }
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
        if (args.length == 1) {
            List<String> completions = new ArrayList<>();
            completions.add("bind");
            completions.add("remove");
            completions.add("list");
            completions.add("reload");
            return filterCompletions(completions, args[0]);
        }
        else if (args.length == 2 && "bind".equalsIgnoreCase(args[0])) {
            List<String> completions = new ArrayList<>();
            completions.add("true");
            completions.add("false");
            return filterCompletions(completions, args[1]);
        }
        return Collections.emptyList();
    }

    private List<String> filterCompletions(List<String> completions, String input) {
        if (input == null || input.isEmpty()) {
            return completions;
        }

        List<String> result = new ArrayList<>();
        String lowerInput = input.toLowerCase();
        for (String completion : completions) {
            if (completion.toLowerCase().startsWith(lowerInput)) {
                result.add(completion);
            }
        }
        return result;
    }

    private void sendUsage(CommandSender sender) {
        sendHelp(sender);
    }

    private boolean handleBindCommand(CommandSender sender, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(LangHelper.getString("errors.player-only"));
            return true;
        }

        if (args.length < 3) {
            sendUsage(sender);
            return true;
        }

        Player player = (Player) sender;
        ItemStack item = player.getInventory().getItemInMainHand();

        if (item == null || item.getType() == Material.AIR || item.getAmount() == 0) {
            player.sendMessage(LangHelper.getString("errors.invalid-item"));
            return true;
        }

        boolean consume;
        try {
            consume = Boolean.parseBoolean(args[1]);
        } catch (IllegalArgumentException e) {
            sender.sendMessage(LangHelper.getString("errors.invalid-boolean"));
            return true;
        }

        StringBuilder commandBuilder = new StringBuilder();
        for (int i = 2; i < args.length; i++) {
            if (i > 2) commandBuilder.append(" ");
            commandBuilder.append(args[i]);
        }
        String command = commandBuilder.toString().trim();

        // 绑定指令到物品
        commandService.bindCommandToItem(item, command, consume);
        sender.sendMessage(LangHelper.getString("commands.bind.success", command, consume));
        return true;
    }

    private boolean handleRemoveCommand(CommandSender sender) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(LangHelper.getString("errors.player-only"));
            return true;
        }

        Player player = (Player) sender;
        ItemStack item = player.getInventory().getItemInMainHand();

        if (item == null || item.getType() == Material.AIR || item.getAmount() == 0) {
            player.sendMessage(LangHelper.getString("errors.invalid-item"));
            return true;
        }

        CommandData data = commandService.getCommandDataByItem(item);
        if (data == null) {
            player.sendMessage(LangHelper.getString("errors.no-command-bound"));
            return true;
        }

        commandService.removeCommandFromItem(item);
        player.sendMessage(LangHelper.getString("commands.remove.success", data.getCommand()));
        return true;
    }

    private boolean handleListCommand(CommandSender sender) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(LangHelper.getString("errors.player-only"));
            return true;
        }

        Player player = (Player) sender;
        ItemStack item = player.getInventory().getItemInMainHand();

        if (item == null || item.getType() == Material.AIR || item.getAmount() == 0) {
            player.sendMessage(LangHelper.getString("errors.invalid-item"));
            return true;
        }

        CommandData data = commandService.getCommandDataByItem(item);
        if (data == null) {
            player.sendMessage(LangHelper.getString("errors.no-command-bound"));
            return true;
        }

        String displayName = "无";
        ItemMeta meta = item.getItemMeta();
        if (meta != null && meta.hasDisplayName()) {
            displayName = meta.getDisplayName();
        }

        player.sendMessage(LangHelper.getString("commands.list.title"));
        player.sendMessage(LangHelper.getString("commands.list.command", data.getCommand()));
        player.sendMessage(LangHelper.getString("commands.list.consume", data.shouldConsume()));
        player.sendMessage(LangHelper.getString("commands.list.name", displayName));
        player.sendMessage(LangHelper.getString("commands.list.type", item.getType().name()));
        return true;
    }

    private boolean handleReloadCommand(CommandSender sender) {
        try {
            ConfigManager.loadMainConfig();
            LangHelper.init(plugin);

            sender.sendMessage(LangHelper.getString("commands.reload.success"));
        } catch (Exception e) {
            sender.sendMessage(LangHelper.getString("commands.reload.error", e.getMessage()));
        }
        return true;
    }

    private void sendHelp(CommandSender sender) {
        LangHelper.getStringList("commands.help").forEach(sender::sendMessage); // 修复键名
    }

}

